<template>
  <customContainer ref="customContainerRef" :config="config" />
  <el-dialog v-model="open" append-to-body fullscreen>
    <detail ref="detailRef"></detail>
  </el-dialog>
  <el-dialog v-model="open2" fullscreen :title="title2">
    <Trajectories ref="traRef"></Trajectories>
  </el-dialog>
</template>
<script lang="ts" setup>
import { ref, getCurrentInstance, computed, defineAsyncComponent } from 'vue'
import { Download, Edit, Bottom, Delete } from '@element-plus/icons-vue'
import { ElButton, ElMessage, ElMessageBox } from 'element-plus'
import { DictDirection } from '@/store/modules/dicts'
import { selectSysOrderInfoEndList, cancelEndInfo } from '@/api/expressManager/terminal'
import Trajectories from '@/components/trajectories/index.vue'

const detail = defineAsyncComponent(() => import('./components/detail.vue'))
const customContainerRef = ref(null),
  detailRef = ref(null),
  traRef = ref(null),
  // 非单个禁用
  single = ref(true),
  // 非多个禁用
  multiple = ref(true),
  {
    appContext: {
      config: {
        globalProperties: { $download },
      },
    },
  } = getCurrentInstance()
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  orderNo: '',
  waybillNo: '',
  mainTransferOrderNo: '',
  cust: '',
  goodsType: '',
  consigneeCountry: '',
  consigneePostcode: '',
  dateRange: '',
  zDdateRange: '',

})
// const { proxy } = getCurrentInstance() as any
const open = ref(false)
const open2 = ref(false)
const title2 = ref(null)
const handleExport = () => {
  const data = queryParams.value
  return $download('order/orderEnd/export', data, `endOrderList_${ new Date().getTime() }.xlsx`)
}
const handleDelete = (row: { [key: string]: any }) => {
  ElMessageBox.confirm('敏感操作，是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    const id = row.id
    const orderNo = row.orderNo
    const customerCode = row.customerCode
    cancelEndInfo(id, orderNo, customerCode).then(res => {
      if (res.code == 200) {
        ElMessage.success('撤单成功!')
        customContainerRef.value.getList()
      } else {
        ElMessage.error(res.mag)
      }
    })
  }).catch(() => {
    ElMessage.info('已取消撤单')
  })
}
const toUps = async (row: { [key: string]: any }) => {
  title2.value = '主转单号轨迹'
  // open2.value = true
  const markerType = row.makerType
  const mainOrder = row.mainTransferOrderNo
  if (!markerType) {
    ElMessageBox.alert('无该订单物流信息')
  } else if (!mainOrder) {
    ElMessageBox.alert('该订单异常，请联系管理员')
  } else {
    ElMessageBox.alert('未写')
    // const rule1 = /ups/gi
    // const rule2 = /fedex/gi
    // const mainOrders = mainOrder.split('|')
    // const data = { trackingNumber: mainOrders }
    // let res
    // try {
    //   if (rule1.test(markerType)) {
    //     res = await orderTrack(data)
    //     console.log(res, data, 1)
    //   } else if (rule2.test(markerType)) {
    //     // res = await getFedexSerachTracking(data)
    //     console.log(res, 111)
    //   } else {
    //     ElMessageBox.alert('订单异常，请联系管理员，记录好订单号')
    //   }
    //   res.code == 200 && (proxy.packageList = res.data)
      
    //   open2.value = true
    // } catch (error) {
    //   console.log(error)
    // }
  }
}
const goDetail = (row: { [key: string]: any }) => {
  open.value = true
  detailRef.value.idss = row.id 
  detailRef.value.getList()
}
const handleDownLabel = (row: { [key: string]: any }) => {
  console.log(row)
  const { labelUrl, makerType, waybillNo, tagInfoId } = row
  if (labelUrl.length != 0) {
    window.open(labelUrl)
  } else if (!labelUrl && makerType && makerType.includes('JD') && makerType.includes('USA')) {
    const data = {
      tagInfoId,
      customerWaybillNo: waybillNo,
    }
    console.log(data)
  }
}
const handleSelectionChange = (rows: { [key: string]: any }[]) => {
  single.value = rows.length != 1
  multiple.value = !rows.length
}
const isGrey = (rows: { [key: string]: any }) => {
  const sp = rows.row.splittingStatusName
  console.log(sp)
  if (sp == '撤单') {
    return { color: '#ccd0d6' }
  }
}

const config = computed({
  get() {
    return {
      query: {
        fields: [
          {
            label: '系统订单号',
            prop: 'orderNo',
            option: {
              type: 'textarea',
            },
          },
          {
            label: '客户单号',
            prop: 'waybillNo',
            option: {
              placeholder: '请输入客户单号',
              type: 'textarea',
            },
          },
         
          {
            label: '主转单号',
            prop: 'mainTransferOrderNo',
            option: {
              type: 'textarea',
            },
          },
          {
            type: 'select',
            label: '客户名称',
            prop: 'customerCode',
            option: {
              dictInfo: { dict: DictDirection.客户 },
            },
          },
          {
            type: 'select',
            label: '收货类型',
            prop: 'goodsType',
            option: {
              dictInfo: { dict: DictDirection.货物类型 },
            },
          },
          {
            type: 'select',
            label: '目的国家',
            prop: 'consigneeCountry',
            option: {
              dictInfo: { dict: DictDirection.国家 },
            },
          },
          {
            label: '邮编',
            prop: 'consigneePostcode',
          },
          
          {
            type: 'date-picker',
            label: '创建日期',
            prop: 'dateRange',
            option: {
              type: 'daterange',
              valueFormat: 'YYYY-MM-DD',
            },
          },
          {
            type: 'date-picker',
            label: '制单时间',
            prop: 'zDdateRange',
            option: {
              type: 'daterange',
              valueFormat: 'YYYY-MM-DD',
            },
          },
          
        ],
        queryParams: queryParams.value,
        formOption: {},
      },
      btns: [
        {
          title: '导出',
          
          onclick: handleExport,
          type: 'warning',
          icon: Bottom,
        },
      ],
      table: {
        columns: [
          { type: 'selection', width: '55' },
          {
            label: '客户名称',
            prop: 'customerName',
            width: '100',
            align: 'center',
          },
          { label: '客户单号', align: 'center', prop: 'waybillNo', width: '120' },
          { label: '主转单号', align: 'center', prop: 'mainTransferOrderNo', width: '120' },
          { label: '系统订单号',
            align: 'center',
            prop: 'orderNo',
            width: '190',
            render(h, params) {
              const buttons = [
                {
                  title: params.row.orderNo,
                  clickFun: toUps,
                },
              ]
              return buttons.map((el) => h(
                ElButton,
                {
                  text: true,
                  type: 'primary',
                  onClick: () => {
                    el.clickFun(params.row)
                  },
                },
                {
                  default: () => el.title,
                },
              ))
            } },
          { label: '总实重', align: 'center', prop: 'receivingTotalWeight', width: '120' },
          { label: '材积重', align: 'center', prop: 'receivingTotalWood' },
          { label: '计费重', align: 'center', prop: 'receivingTotalCharging', width: '120' },
          { label: '件数', align: 'center', prop: 'receivingTotal', width: '120' },
          { label: '订单状态',
            align: 'center',
            prop: 'splittingStatus',
            width: '120',
            autoFormatter: {
              dict: DictDirection.包裹状态,
              rowKey: 'splittingStatus',
            } },
          { label: '创建日期', align: 'center', prop: 'createDate' },
          { label: '邮编', align: 'center', prop: 'consigneePostcode', width: '100' },
          { label: '国家',
            align: 'center',
            prop: 'consigneeCountry',
            autoFormatter: {
              dict: DictDirection.国家,
              rowKey: 'consigneeCountry',
            } },
          { label: '货物类型',
            align: 'center',
            prop: 'goodsType',
            autoFormatter: {
              dict: DictDirection.货物类型,
              rowKey: 'goodsType',
            },
          },
          { label: '制单日期', align: 'center', prop: 'makerDate', width: '120' },
          { label: '备注', align: 'center', prop: 'remarks', width: '100' },
          {
            label: '操作',
            align: 'center',
            width: '360',
            fixed: 'right',
            showOverflowTooltip: false,
            render(h, params) {
              const buttons = [
                {
                  title: '撤单',
                  icon: Delete,
                  disabled: params.row.splittingStatusName == '撤单',
                  clickFun: handleDelete,
                },
                {
                  title: '详情',
                  icon: Edit,
                  clickFun: goDetail,
                },

                {
                  title: '下载标签',
                  icon: Download,
                  clickFun: handleDownLabel,
                },
              ]
              return buttons.map((el) => h(
                ElButton,
                {
                  text: true,
                  type: 'primary',
                  icon: el.icon,
                  onClick: () => {
                    el.clickFun(params.row)
                  },
                },
                {
                  default: () => el.title,
                },
              ))
            },
          },
        ],
        event: {
          onSelectionChange: (rows) => {
            handleSelectionChange(rows)
          }, 
          rowStyle: (rows) => {
            isGrey(rows)
          },         
        },
        
      },
      
      api: selectSysOrderInfoEndList,
      customKey: 'express/mainBusiness/terminalServices/terminalOrder',
    }
  },
  set(val) {
    return val
  },
})
</script>